package com.dreamstall.xiaome;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;


import org.apache.http.client.ClientProtocolException;

public class EXiaoMeThread implements Runnable {

	private Map<String,Word> ready_map ;
	
	public EXiaoMeThread(Map<String,Word> ready_map){
		this.ready_map = ready_map;
	}
	
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("XiaomE Strart");
		Set<String> words = new Spider().getWords();
		String fromFormat = "HH";
		SimpleDateFormat  format = new SimpleDateFormat (fromFormat);
		TimeZone zone = TimeZone.getTimeZone("GMT+8");
		format.setTimeZone(zone);
		while(true){
			  Date myDate = new Date();
			  int hour = Integer.parseInt(format.format(myDate)) ;
			  if(hour>7&&hour<23){
				  String word = "" ;
				  Word value = new Word();
				  if(new Random().nextInt(8)==1){
					  words.addAll( new Spider().getWords());
				  }
				  if(ready_map.size()>10&&(new Random().nextInt(100))>50){
					  word = (String)(ready_map.keySet().toArray()[new Random().nextInt(ready_map.size())]);
				  }else{
					  word = (String)words.toArray()[new Random().nextInt(words.size())];
				  }
				  
				  value = ready_map.get("word");
				  if(value==null||value.equals("")){
					  for(int i=0;i<15;i++){
						  value = new Spider().translate(word);
						if (!value.equals(""))
							break;
					  }
				  }
				  String msg = value.toString() ;
				  try {
					new Spider().getContext("http://dreamstall.com/msn/?msg="
								+ URLEncoder.encode(msg), "utf-8");
					ready_map.put(word, value);
					System.out.println(msg);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			  }
			  int random = new Random().nextInt(600);
			  long millis = (60*15)+random-300 ;
			  System.out.println("睡眠"+millis+"秒");
			  millis = millis*1000 ;
			  try {
				  Thread.sleep(millis);
			  } catch (InterruptedException e) {
				  // TODO Auto-generated catch block
				  e.printStackTrace();
			  }
		}
	}
	public static void main(String[] args) {
		Map<String, Word> ready_words = new HashMap<String, Word>();
		new Thread(new EXiaoMeThread(ready_words)).start();
	}
}
